const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const pool = require('../models/database.js');

// 获取所有宠物
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM pet_list');
    res.json({
      code: 200,
      message: '获取成功',
      data: rows
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: err.message
    });
  }
});

// 获取单个宠物详情
router.get('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.query('SELECT * FROM pet_list WHERE id = ?', [id]);
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '宠物不存在'
      });
    }
    res.json({
      code: 200,
      message: '获取成功',
      data: rows[0]
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: err.message
    });
  }
});

// 新增宠物
router.post('', async (req, res) => {
  try {
    const {
      name, type, breed, age, gender, weight,
      img, images, description, price, isAdopted,
      location, latitude, longitude, tags,
    } = req.body;

    const id = uuidv4();

    await pool.query(
      `INSERT INTO pet_list
       (id, name, type, breed, age, gender, weight, img, images, description, price, isAdopted, location, latitude, longitude, tags)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        id,
        name,
        type,
        breed || null,
        age || null,
        gender || null,
        weight || null,
        img || null,
        images ? JSON.stringify(images) : null,
        description || null,
        price || 0,
        isAdopted ? 1 : 0,
        location || null,
        latitude || null,
        longitude || null,
        tags ? JSON.stringify(tags) : null,
      ]
    );

    res.status(201).json({
      code: 201,
      message: '新增成功',
      data: { id }
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 500,
      message: '新增失败',
      error: err.message
    });
  }
});

// 更新宠物信息
router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const {
    name, type, breed, age, gender, weight,
    img, images, description, price, isAdopted,
    location, latitude, longitude, tags,
  } = req.body;

  try {
    const [result] = await pool.query(
      `UPDATE pet_list SET
        name = ?, type = ?, breed = ?, age = ?, gender = ?, weight = ?,
        img = ?, images = ?, description = ?, price = ?, isAdopted = ?,
        location = ?, latitude = ?, longitude = ?, tags = ?
      WHERE id = ?`,
      [
        name,
        type,
        breed || null,
        age || null,
        gender || null,
        weight || null,
        img || null,
        images ? JSON.stringify(images) : null,
        description || null,
        price || 0,
        isAdopted ? 1 : 0,
        location || null,
        latitude || null,
        longitude || null,
        tags ? JSON.stringify(tags) : null,
        id,
      ]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '宠物不存在'
      });
    }

    res.json({
      code: 200,
      message: '更新成功',
      data: null
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 500,
      message: '更新失败',
      error: err.message
    });
  }
});

// 删除宠物
router.delete('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    const [result] = await pool.query('DELETE FROM pet_list WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '宠物不存在'
      });
    }

    res.json({
      code: 200,
      message: '删除成功',
      data: null
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 500,
      message: '删除失败',
      error: err.message
    });
  }
});

module.exports = router;
